import time

from rest_framework.views import APIView
from bases.response import Response
from django.http import HttpResponsePermanentRedirect,HttpResponseRedirect
from django.shortcuts import redirect

from utils.make_short_url import PADDING
from utils.make_short_url import id_turn_to_code
from utils.sha256_short_url import generate_short_url
from bases.logger import logger
from api import models
import time

class CreateShortUrl(APIView):
    def get(self,request):
        return Response()
    def make_short_url(self,long_url,merge_id):
        code = generate_short_url(long_url)
        obj = models.URLMapping.objects.create(
            short_code=code,
            long_url=long_url,
            merge_id=merge_id
        )
        return code
    def post(self,request):
        # 待记录的long_url
        long_url = request.data.get('long_url')
        merge_id = request.data.get("merge_id")
        # # 记录到数据库中
        # obj = models.URLMapping(long_url=long_url)
        # obj.save()
        # # 通过id转成字符串
        # code = id_turn_to_code(obj.pk)
        # # 记录字符串原始长度
        # obj.soure_code_len = len(code)
        # # 对于不足8位的字符串填充Z
        # code = code.ljust(8,PADDING)
        # obj.short_code = code
        # obj.save()
        msg = ''
        for i in range(10):
            try:
                short_code = self.make_short_url(long_url=long_url,merge_id=merge_id)
                data = {
                    'short_code': short_code,
                    'long_url': long_url
                }
                return Response(data=data)
            except Exception as e:
                msg = str(e)
                logger(msg)
        else:
            return Response(code=400,msg=msg)

    def put(self,request):
        merge_id = request.data.get("merge_id")
        long_url = request.data.get("long_url")
        if not merge_id:
            return Response(code=400,msg="没有携带合并id")
        if not long_url:
            return Response(code=400,msg="没有携带长链接")
        try:
            # 修改长链接
            models.URLMapping.objects.filter(
                merge_id=merge_id
            ).update(
                long_url=long_url
            )
            logger(f"{merge_id}的长链接{long_url}")
            return Response(code=200,msg='更新成功')
        except Exception as e:
            logger(f'数据库报错，{e}，merge_id={merge_id},')
            return Response(code=400,msg="数据库报错")


class RedirectShortUrl(APIView):
    authentication_classes = []
    def get(self,request,code):
        obj = models.URLMapping.objects.filter(short_code=code).first()
        if obj:
            long_url = obj.long_url
            obj.count+=1
            obj.save()
            # 使用临时重定向302，浏览器不会缓存long_url
            return HttpResponseRedirect(long_url)
        else:
            return Response(code=400,msg='查询不到记录')
